import org.apache.commons.io.IOUtils
import org.apache.commons.fileupload.util.Streams
import org.apache.commons.fileupload.servlet.ServletFileUpload
import java.io.*;
import com.google.appengine.api.datastore.Entity
import com.google.appengine.api.datastore.Blob
import com.google.appengine.api.datastore.Key
import com.google.appengine.api.images.* 


/* gets image upload. From Mr. Haki's blog - http://mrhaki.blogspot.com/2009/11/add-file-upload-support-to-groovlets-in.html */
uploads = [:]  // Store result from multipart content.
if (ServletFileUpload.isMultipartContent(request)) {
 def uploader = new ServletFileUpload()  
 def items = uploader.getItemIterator(request)
 while (items.hasNext()) {
	 def item = items.next()
	 def stream = item.openStream()
	 try {
		 if (item.formField) {  // 'Normal' form field.
			 	params[item.fieldName] = Streams.asString(stream)
		 } else {
			 uploads[item.fieldName] = [
			                            name: item.name,
			                            contentType: item.contentType,
			                            data: IOUtils.toByteArray(stream)
			                            ]
	 }
	 } finally {
		 IOUtils.closeQuietly stream
	 }
 }
 
 
}


def concello = params.concello
def titulo = params.titulo
def ano = params.ano
//examina uploads
if (uploads['imagen']?.data && concello && titulo && ano) {
	
	
	//Blob elBlob = uploads['imagen'].data as Blob
	byte[] datosImagen = uploads['imagen'].data
	Blob b = new Blob(datosImagen)
	
	Entity entity = new Entity("foto")
	entity.nombre="Una foto"
	entity.imaxe = b
	entity.titulo = titulo
	entity.concello = concello
	entity.dataCreacion = new Date()
	entity.ano = ano
	
	
	
	 Image oldImage = ImagesServiceFactory.makeImage(datosImagen) 
   
   	 CompositeTransform cp = ImagesServiceFactory.makeCompositeTransform()
   	 Transform resize = ImagesServiceFactory.makeResize(400,300)
   	 cp.concatenate( resize )
   	 
   	 CompositeTransform cpThumb = ImagesServiceFactory.makeCompositeTransform()
   	 Transform resizeThumb = ImagesServiceFactory.makeResize(200,150)
   	 cpThumb.concatenate( resizeThumb )
   	 
   	 Image pic = images.applyTransform( cp, oldImage, ImagesService.OutputEncoding.valueOf("JPEG"))
   	 Image picThumb = images.applyTransform( cpThumb, oldImage, ImagesService.OutputEncoding.valueOf("JPEG"))
   	 
   	 Blob blobThumb = new Blob(picThumb.imageData)
   	 entity.thumb = blobThumb
   	 entity.save()
   	 
	 response.setContentType(uploads['imagen'].contentType)
	 sout << pic.imageData
	 //println "content = " + uploads['imagen'].contentType
	
	
}

